package com.xk.user.controller;

import com.xk.user.pojo.User;
import com.xk.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.io.UnsupportedEncodingException;

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 校验数据
     * @param data  要校验的数据
     * @param type 要校验的数据类型：1，用户名；2，手机；
     * @return
     */
    @GetMapping("check/{data}/{type}")
    public ResponseEntity<Boolean> checkData(@PathVariable("data") String data,
                                             @PathVariable("type") Integer type){

        return ResponseEntity.ok(userService.checkData(data,type));

    }

    /**
     * 发送短信验证码
     * @param phone 手机号码
     * @return
     */
    @PostMapping("send")
    public ResponseEntity<Void> sendSms(@RequestParam("phone") String phone){
        userService.sendSms(phone);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    /**
     * 用户注册
     * @param user
     * @param code
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, @RequestParam("code") String code) throws UnsupportedEncodingException {

        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();

    }

    /**
     * 通过用户名和密码查询用户
     * @param username
     * @param password
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<User> queryUserBynameAndPwd(@RequestParam("username") String username,
                                                      @RequestParam("password") String password){

        User user = userService.queryUserBynameAndPwd(username, password);
        return ResponseEntity.ok(user);

    }

}
